"use client";
import { FC, PropsWithChildren, useState } from "react";
import HeaderBack from "@/components/HeaderBack";
import ButtonOwn from "@/components/ButtonOwn";
import DomainFooter from "@/components/DomainFooter";
import './page.scss'
import React from "react";
import { phoneRegex } from "@/utils";
import {getCheckUserPhoneExistApi} from "@/api/user";
import { useRouter } from "@/i18n";
import { useTranslations } from "next-intl";

interface Props {}

const ResetPhone: FC<PropsWithChildren<Props>> = () => {
    const t = useTranslations("ResetPhonePage");
    const router:any = useRouter()
    let [userPhone, setUserPhone] = useState('')
    const changeUserPhone = (e: { target: { value: any; }; }) => {
        setUserPhone(e.target.value)
    }
    let [msgError, setMsgError] = useState('')
    const blurVerifyPhone = (e: { target: { value: any; }; }) => {
        const {value} = e.target;
        if (value == '') {
            setMsgError('')
            return
        }
        if (value && !phoneRegex(value)) {
            setMsgError(t('enterCorrectphone'))
            return
        }
        setMsgError('')
    }
    const checkUserPhoneRequest = async () => {
        if(!phoneRegex(userPhone)) return
        let { code, msg, data } = await getCheckUserPhoneExistApi({user_phone: userPhone})
        if(code == 200 && data) {
            router.push(`/verification?userPhone=${userPhone}`)
            return
        }
        setMsgError(msg)
    }
    return (
        <div className="resetPhone-box">
            <HeaderBack />
            <div className="main">
                <div className="title">
                    <h2>{t('h2')}</h2>
                    <div>{t('h3')}</div>
                </div>
                <div className="phoneInput">
                    <span className="after">{t('areaCode')}</span>
                    <input type="tel" value={userPhone} onChange={changeUserPhone} onBlur={blurVerifyPhone} placeholder={t('Celular')} maxLength={11} />
                </div>
                { msgError && <div className="tips"> {msgError} </div> }
                <div className="btnContent">
                    <ButtonOwn active={userPhone.length == 11} callbackFun={checkUserPhoneRequest}>{t('Continuar')}</ButtonOwn>
                </div>
            </div>
            <DomainFooter />
        </div>
    );
};

export default ResetPhone;
